<!-- 个人信息/基本资料 -->
<template>
	<view class="basicInformation">
		<view class="myNmae flex-between">
			<text>你的姓名</text>
			<input class="font-overflow" v-model="form.technicianName" placeholder="请输入姓名" />
		</view>
		<view class="myNmae flex-between">
			<text>你的电话</text>
			<input maxlength="11" type="number" v-model="form.mobile" placeholder="请输入联系方式" />
		</view>
		<view class="myNmae flex-between">

			<text>意向城市</text>
			<view class="flex-align-center">
				<city-sel  ref="citys" :title=form.city @getCity="getCity"></city-sel>
				<!-- <image src="/static/my/right-arrow.png" class="v-img m-left10"></image> -->
			</view>
			<!-- <input class="font-overflow" v-model="form.city" placeholder="选择意向城市" /> -->
		</view>
		<view class="myNmae flex-between">
			<text>详细地址</text>
			<input class="font-overflow" v-model="form.address" placeholder="点击获取详细地址" />
		</view>
		<view class="flex-between myNmae">
			<text>您的性别</text>
			<radio-group v-model="form.gender" name="apply" @change="handleApplyType">
				<label class="m-right10">
					<radio :checked="form.gender ==1" class="min-radio" :value=1  color="#67C23A"  />
					<text>男</text>
				</label>
				<label>
					<radio :checked="form.gender ==2" class="min-radio" :value=2  color="#67C23A" />
					<text>女</text>
				</label>
			</radio-group>
		</view>

		<view class="flex-between myNmae">
			<text>您的年龄</text>
			<input type="number" maxlength="3" v-model="form.age" placeholder="请输入年龄" />
		</view>
		<view class="myNmae flex-between">
			<text>从业时间</text>
			<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
				<view class="flex-align-center color6" v-if="yeartime">
					{{ yeartime }}
					<text>-</text>
					{{ monthtime }}
					<text>-</text>
					{{ daytime }}
				</view>
				<view class="flex-align-center color6" v-else>请选择从业时间</view>
			</picker>
			<!-- <text>请选择从业时间</text> -->
		</view>
		<view class="personalLntroduction">
			<view>
				<text>生活照片</text>

			</view>
			<view>
				<!-- 生活图片 -->
				<sunui-upimg1 :border="'1px dashed #bfbfbf'" :formData="imgFormData" :storageMode="storageMode"
					:header="header" :size="['200rpx', '200rpx']" btnName="上传图片" :uploadServerUrl="upPicUrl"
					ref="selectimgandupload1" @uploaded="imgLoaded1" @change="imgsChange1" :maxFileNumber="9"><template
						v-slot:icon>
						<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
					</template></sunui-upimg1>
			</view>
		</view>
		<view class="personalLntroduction">
			<view>
				<text>员工介绍</text>
				<text class="describe">(请输入10个字以上介绍自己优势)</text>
			</view>
			<view class="textarea-box">
				<textarea v-model="form.personalLntroduction" placeholder="请输入自己的个人优势" maxlength="50" @input="descInput"
					style="height: 150rpx;" />
				<view class="textarea-color">{{ remnant }}/50</view>
			</view>
		</view>
		<view class="personalTags">
			<view>
				<text>员工标签</text>
				<view class="tag_container">
					<zy-tag ref="zyAddTag" addible closable @delete="deleteTag(item)"
						v-for="(item, index) in tagAddList" :text="item"></zy-tag>
					<view class="zy_tag_add"><text class="zy_tag_add_input" @click="addTag">+ 自定义</text></view>
				</view>
			</view>
		</view>
		<view class="sumbit-btn flex" @click="submitInformation()">提交</view>
		<!-- 添加标签 弹出框 -->
		<sunui-popup ref="pop">
			<template v-slot:content>
				<view class="v-pop-cls flex-column">
					<image src="/static/close.png" @click="closeTag"></image>
					<text>添加标签</text>

					<input placeholder="请输入2到6个字标签" v-model="singleLabel" />
					<view class="flex" @click="singleLabelClick()">添加</view>
				</view>
			</template>
		</sunui-popup>
	</view>
</template>

<script>
	import {
		object2Url
	} from '@/utils/trans';
	import {

		mapMutations
	} from 'vuex'
	import {
		mapState
	} from 'vuex'
	import {
		mapGetters
	} from 'vuex'
	import zyTag from '@/uni_modules/zy-tag/components/zy-tag/zy-tag.vue'
	export default {

		components: {
			zyTag
		},
		data() {
			const currentDate = this.getDate({
				format: true
			});
			return {
				photos: 'http://tmp/oPvxqRtPPstDa128a34f30dbb644483d8ec6e94e75c9.jpg',
				upPicUrl: '',
				imgFormData: null,
				alyOssSignatureInfo: null,
				header: null,
				timeDate: '',
				suffix: '',
				// 上传图片的数组
				uploaderArr: [],
				imgViewArr: [],
				imgStr: [],
				file: [],
				form: {

					technicianName: '', //姓名
					gender: 1, //性别
					address: '', //详细地址
					mobile: '', //电话
					city: '', //城市
					age: '', //年龄
					// 从业时间end
					employmentTime: '',
					personalLntroduction: '', //个人介绍
					lifePhotos: '',
					label: '', // 个人标签——多个以逗号间隔
				},
				addValue: '',
				singleLabel: '', // 单个标签覆盖
				//添加标签数据
				tagAddList: [],
				//选择的年份
				yeartime: currentDate.split('-')[0],
				//选择的月份
				monthtime: currentDate.split('-')[1],
				//选择的天数
				daytime: currentDate.split('-')[2],
				remnant: 0,
				basicInformationForm: {

				},
				technicianDetail: {},
				storageMode: '',
			


			};
		},
		onLoad() {
			this.$nextTick(() => {
				this.$refs.citys.getCate();
			});
			this.init()
			this.initImg()
			this.getUploadConfig()
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			},
			// 将 m_user 模块中的 userinfo 映射到当前页面中使用
			...mapState('user', ['basicAuthenticationForm', 'uploadQualificationForm', 'uploadHealthCertificateForm',
				'uploadAvatarForm', 'identityAuthenticationForm', 'technicianDetails'
			]),

		},
		methods: {
			...mapMutations('user', ['basicAuthentication', 'uploadProgress', 'uploadTaskCenter', 'technicianDetailsFn']),
			initImg() {
				if (this.technicianDetails.authenticationNot == 3) {
					this.$sun.assignObject(this.form, {
						...this.technicianDetails
					})
					this.form.gender=this.technicianDetails.gender
					console.log(this.form)
					console.log(this.form.lifePhotos)
					const imgStr = this.form.lifePhotos
					if (imgStr?.length) {
						if (imgStr.includes(',')) {
							console.log('字符串中包含逗号');
							// 包含的进行slice(',') 分割

							this.imgStr = imgStr.split(',').map((item) => item.trim());
							console.log(this.imgStr)
							this.$refs.selectimgandupload1.setItems(this.imgStr);
						} else {
							console.log('字符串中不包含逗号');
							this.imgStr = imgStr.split();
							this.$refs.selectimgandupload1.setItems(this.imgStr);
						}

						this.viewerVisible = true;
					}

				}
			},
			getCity(e) {
				console.log('获取城市的文字===', e);
				this.form.city = e;
			},
			async getUploadConfig() {
				const result = await this.$http.get({
					url: this.$api.getStorageConfig,
					data: {}
				});
				if (result.code == 200) {
					this.storageMode = result.data.storageMode; // storageMode:2是‘阿里云’上传，3是‘七牛云’ 上传
					console.log('this.storageMode', this.storageMode);

				} else {
					console.log('result.message', result.message);
				}
			},



			// “上传图片”发生改变
			imgsChange1(file) {
				// 文件名
				this.timeDate = new Date().getTime();
				console.log('上传发生改变this.storageMode1111============', this.storageMode, '参数file', file);
				// 如果是2 上传  阿里云 3  七牛云
				if (this.storageMode == 2) {
					this.userOssSignature(file);
				}
				if (this.storageMode == 3) {
					this.upPicUrl = this.$api.qnyOssSignature;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});
				}
			},
			// 阿里云上传
			async userOssSignature(file) {

				console.log('this阿里云上传进入=======');
				const ts = new Date().getTime();
				const us = {
					ts
				};
				let url = this.$api.alyOssSignature + `${object2Url(us)}`;
				const res = await this.$http.get({
					url: url,
					data: {
						us: us
					}
				});
				this.ossInfo = res.data;
				this.upPicUrl = this.ossInfo?.host;
				// 获取上传图片名称和后缀
				console.log(file)

				if (file.length) {
					let fileUrl = file[0].url;
					let markIndex = fileUrl.lastIndexOf('.');
					this.suffix = fileUrl.substring(markIndex); //后缀

					console.log('this.ossInfo', this.ossInfo);
					this.imgFormData = {
						name: this.timeDate + this.suffix,
						key: this.timeDate + this.suffix, //上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
						policy: this.ossInfo.policy,
						OSSAccessKeyId: this.ossInfo.accessId,
						success_action_status: '200',
						signature: this.ossInfo.signature
					};
					this.header = {
						'Access-Control-Allow-Origin': '*',
						'x-oss-callback-Authorization': 'access_token'
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});
					console.log('页面阿里云url22222222222222', this.ossInfo?.host + '/' + this.timeDate + this.suffix);
				} else {
					this.imgStr = []
				}

			},

			// 上传图片返回
			imgLoaded1(e) {
				console.log('上传返回eeeee222============', e);
				try {
					this.img = [];
					for (let i = 0; i < e.length; i++) {
						this.img.push(e[i].url);
					}
				} catch (e) {
					this.img = [];
				}
				console.log('this.img=======', this.img);
				this.imgStr = this.img
				console.log(this.imgStr)
				this.form.lifePhotos = this.imgStr.length === 1 ? this.imgStr[0].toString() : this.imgStr.join(',');
			},
			init() {
				console.log(this.technicianDetails)
				if (this.technicianDetails.authenticationNot == 3) {
					this.$sun.assignObject(this.form, {
						...this.technicianDetails
					})
					this.tagAddList = this.form.label.split(',')
					const time = this.form.employmentTime.split('-')
					console.log(time)
					this.yeartime = time[0],
						this.monthtime = time[1],
						this.daytime = time[2]
					console.log(this.form)
				}
			},
			// 备注
			descInput(e) {
				this.remnant = e.detail.value.length;
				if (this.remnant >= 50) {
					this.$sun.toast('说明字数已达上限');
				}
			},

			// 选择日期
			bindDateChange: function(e) {
				this.date = e.target.value;
				/* 在上面声明变量，split是用来截取字段*/
				this.yeartime = this.date.split('-')[0];
				this.monthtime = this.date.split('-')[1];
				this.daytime = this.date.split('-')[2];
			},
			// 日期获取
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}

				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			// 选择性别
			handleApplyType(e) {
				let val = e.detail.value;
				this.form.gender =val;
				console.log(e.detail.value);
			},

			//删除标签
			deleteTag(item) {
				console.log(item);
				// 2种删除方式
				// this.tagDeleteList.splice(this.tagDeleteList.indexOf(item), 1);
				this.tagAddList = this.tagAddList.filter(o => {
					return o !== item;
				});
			},
			// ‘添加标签’弹出框
			addTag() {
				this.$refs.pop.show({
					anim: 'center',
					shadeClose: false,
					topclose: false
				});
			},
			// 弹窗——添加/修改单个标签
			singleLabelClick() {
				if (!this.singleLabel) {
					this.$sun.toast('请先输入标签');
				} else {
					this.updateTags();
				}
			},
			// 技师员工标签添加修改
			async updateTags() {
				// const result = await this.$http.put({
				// 	url: this.$api.updatePersonalTags,
				// 	data: {
				// 		id: '2', //修改时传值
				// 		label: this.singleLabel //添加的标签值
				// 	}
				// });


				this.$sun.toast('添加成功！');
				this.addTag2()
				this.closeTag();
			},

			// 关闭 ‘添加标签’弹出框
			closeTag() {
				this.$refs.pop.close();
			},
			//添加标签input框回车事件
			addTag2() {
				this.tagAddList.push(this.singleLabel);
				this.form.label = this.tagAddList.join(",")
				this.singleLabel = '';
			},

			// 提交信息
			async submitInformation() {
				if (!this.form.technicianName) {
					this.$sun.toast('请输入姓名');
					return false;
				} else if (!this.form.mobile) {
					this.$sun.toast('请输入联系方式');
					return false;
				} else if (!/^1[3456789]\d{9}$/.test(this.form.mobile)) {
					this.$sun.toast('请输入正确的联系方式');
					return false;
				} else if (!this.form.city) {
					this.$sun.toast('请选择意向城市');
					return false;
				} else if (!this.form.address) {
					this.$sun.toast('请获取详细地址');
					return false;
				} else if (!this.form.age) {
					this.$sun.toast('请输入年龄');
					return false;
				} else if (!this.yeartime) {
					this.$sun.toast('请选择您的从业时间');
					return false;
				} else {
					this.$at.uniDoFunc({
						// 键名
						key: 'submit',
						success: async () => {
							//锁定
							this.$at.lockKey('submit');
							this.save();
						}
					});
					
				}
			},

			// 保存数据
			async save() {
				// if(){

				// }
				if (this.technicianDetails.authenticationNot == 4) {
					console.log(this.technicianDetails)
					this.formData = this.technicianDetails
					const allForm = {
						...this.formData,
						...this.form
					}
					console.log(JSON.stringify(allForm) + '========================')
					const saveRes = await this.$http.put({
						url: this.$api.technicianModifyIphone,
						data: {
							...allForm,
							authenticationNot: 1
						}
					});
					this.technicianDetail = allForm
					console.log(saveRes.data + '======================')
					this.technicianDetailsFn(this.technicianDetail ? this.technicianDetail : {})
					this.uploadProgress({
						status: true,
						name: 'serviceItemsEnd'
					})
					this.uploadTaskCenter({
						status: true,
						name: 'signtHheAgreement'
					})
					this.$at.releaseKey('submit');
					this.$sun.navSwitch('/pages/my/my');
				};
				console.log(this.technicianDetails?.authenticationNot !== 1 +
					'=================================================')
				if (this.technicianDetails.authenticationNot == 3) {
					console.log(this.technicianDetails)
					this.formData = this.technicianDetails
					const allForm = {
						...this.formData,
						...this.form
					}
					console.log(JSON.stringify(allForm) + '========================')
					const saveRes = await this.$http.put({
						url: this.$api.technicianModifyIphone,
						data: {
							...allForm
						}
					});
					this.technicianDetail = allForm
					console.log(saveRes.data + '======================')
					this.technicianDetailsFn(this.technicianDetail ? this.technicianDetail : {})
					this.$at.releaseKey('submit');
					this.$sun.navBack();
				} else if (this.technicianDetails?.authenticationNot !== 1 && this.technicianDetails
					?.authenticationNot !== 4) {
					let employmentTime = this.yeartime + '-' + this.monthtime + '-' + this.daytime;
					this.form.employmentTime = employmentTime
					this.uploadProgress({
						status: true,
						name: 'serviceItemsEnd'
					})
					this.uploadTaskCenter({
						status: true,
						name: 'signtHheAgreement'
					})
					this.basicAuthentication(this.form)
					this.basicInformationForm = {
						...this.basicAuthenticationForm,
						...this.identityAuthenticationForm
					}
					this.basicInformationForm.head = this.uploadAvatarForm
					this.basicInformationForm.healthCertificate = this.uploadHealthCertificateForm
					this.basicInformationForm.qualificationCertificate = this.uploadQualificationForm,

						console.log(this.basicInformationForm)
					// 提交所有的认证信息
					const res = await this.$http.put({
						url: this.$api.savePersonalInformation,
						data: {
							...this.basicInformationForm,
							userId: uni.getStorageSync('userId'),
							siteId: uni.getStorageSync('siteId'),
							authenticationNot: 1,
						}
					});

					if (res.code == 200) {

						this.$at.releaseKey('submit');
						this.$sun.navSwitch('/pages/my/my');
					} else {
						this.$at.releaseKey('submit');
						console.log('result.msg', result.msg);
						this.$sun.navSwitch('/pages/my/my');
					}
				}




			}
		}
	};
</script>

<style lang="less">


	page {
		background-color: #ffffff;
	}

	.basicInformation {
		padding: 0 34rpx 50rpx;

		.myNmae {
			padding: 34rpx 0;
			background-color: #fff;

			input {
				text-align: right;
			}
		}

		.personalLntroduction {
			.textarea-box {
				margin-top: 24rpx;
				border: 2rpx dashed #1e6ceb;
				background: #fff;
				padding: 30rpx;
				border-radius: 20rpx;

				.textarea-color {
					text-align: right;
					color: #999;
				}
			}
	.sunui-pop-main {
		z-index: 900;
	}
			.describe {
				margin-left: 10rpx;
				color: #666;
				font-size: 14px;
			}

			margin-top: 50rpx;
		}

		.personalTags {
			margin: 36rpx 0;

			.tag_container {
				margin-top: 36rpx;
				display: flex;
				align-items: center;
				flex-direction: row;
				// justify-content: space-between;
				flex-wrap: wrap;
			}

			.zy_tag_add {
				width: 150rpx;
				height: 50rpx; //medium：45rpx；small：40rpx；mini：35rpx
				padding: 5rpx 15rpx;
				margin: 5rpx 8rpx;
				// border: 1rpx solid $zy-classic-grey;
				border-radius: 10rpx;
				text-align: center;
			}
		}

		.sumbit-btn {
			height: 100rpx;
			color: #ffffff;
			border-radius: 10px;
			background: #1890ff;
		}

		// “添加标签” 弹出框
		.v-pop-cls {
			padding: 46rpx 0 88rpx;
			width: 710rpx;
			height: auto;
			position: relative;
			border-radius: 20rpx;
			background: #fff;

			image {
				width: 52rpx;
				height: 52rpx;
				position: absolute;
				padding: 30rpx;
				top: 0rpx;
				right: 0rpx;
			}

			text {
				color: #000;
				font-size: 36rpx;
			}

			input {
				// text-align: center;
				padding: 0 20rpx;
				width: 608rpx;
				height: 94rpx;
				margin: 62rpx 0;
				border-radius: 20rpx;
				background: #f5f5f5;
			}

			view {
				width: 638rpx;
				height: 88rpx;
				background: #1890ff;
				color: #fff;
				font-size: 32rpx;
			}
		}
	}
</style>